var pageObj={type:"1-121",width:[340],height:[0,,35],htmlObj:["containerDiv"],paging:true,size:15};
var layoutContainer = create_layout(pageObj);
layoutContainer.layout.items[0].showHeader();
layoutContainer.layout.items[0].setText("<span style='font-weight:bold;color:#206988;'>导航菜单</span>");
layoutContainer.layout.items[1].showHeader();
layoutContainer.layout.items[1].setText("<span style='font-weight:bold;color:#206988;'>字典列表</span>");
var hosDictGroupGrid,hosDictGrid,hosDictGroupToolbar,hosDictToolbar;
var dhxWins,editHosDictWin,editHosDictGroupWin;
var oneHosDictGroupInfo,oneHosDictInfo,s_groupCode;
var rondomNum;

$(function(){
	$('.dhtmlxLayoutPolySplitterVer div').css("width","3px");//分割线
	hosDictGroupGrid = layoutContainer.grid[0];
	hosDictGrid = layoutContainer.grid[1];
	layoutContainer.layout.items[0].showHeader();
	layoutContainer.layout.items[0].setText("字典列表");
	layoutContainer.layout.items[1].showHeader();
	layoutContainer.layout.items[1].setText("枚举信息");
	hosDictGroupToolbar = layoutContainer.layout.items[0].attachToolbar({});
 	hosDictGroupToolbar.setIconsPath(basePath + "public/images/main/button/toolbar/");
	hosDictGroupToolbar.addButton("add", 1, "新增", "add.png", "");
	hosDictGroupToolbar.addButton("edit", 2, "编辑", "edit.png", "");
	hosDictGroupToolbar.addButton("del", 2, "删除", "delete.png", "");
	hosDictGroupToolbar.addInput("hosDictGroupContent",3,"输入字典名称",90);
	hosDictGroupToolbar.addButton("search", 4, "查询", "viewStock.png", "");
	hosDictGroupToolbar.setAlign("right");
	hosDictGroupToolbar.attachEvent("onClick", doOnClickHosTool);
	hosDictToolbar = layoutContainer.layout.items[1].attachToolbar({});
	hosDictToolbar.setIconsPath(basePath + "public/images/main/button/toolbar/");
	hosDictToolbar.addButton("add", 1, "新增", "add.png", "");
	hosDictToolbar.addButton("edit", 2, "编辑", "edit.png", "");
 	hosDictToolbar.addButton("refresh", 3, "刷新", "refresh.png", "");
	hosDictToolbar.addButton("del", 4, "删除", "delete.png", "");
 	hosDictToolbar.addInput("hosDictSearchKey",6,"输入枚举名称",100);
 	hosDictToolbar.addButton("search", 7, "查询", "viewStock.png", "");
	hosDictToolbar.attachEvent("onClick", doOnClickDocTool);
   	initHosDictGrid();
	initHosDictGroupGrid();
	layoutContainer.layout.attachEvent("onPanelResizeFinish",function(){
		if(layoutContainer.layout.items[0].getWidth()>380){
			$func.alert("当前宽度已到达最大限制","red");
			layoutContainer.layout.items[0].setWidth(380);
		}
    });

	doHosDictGroupSearch();
	//----------------------------------------------------------------!!!样式!!!
	$('#pagingArea').css({"height":"30px","bottom":"5px","left":"334px"});//分页
	$('.inp').focus(function(){
		this.value='';
	});

	//增加搜索键盘事件
	hosDictGroupToolbar.attachEvent("onEnter", function(id, value){
		doHosDictGroupSearch();
	});
	hosDictToolbar.attachEvent("onEnter", function(id, value){
		doHosDictSearch();
	});

});
function doOnClickDocTool(id){
	switch (id) {
		case 'add':	doEdit('add');break;
		case 'edit': doEdit('edit');break;
		case 'search':doHosDictSearch();break;
		case 'refresh':doRefresh();break;
		case 'del':doDel('del');break;
	}
}
function doOnClickHosTool(id){
	switch (id) {
		case 'add':	doEditGroup('add');break;
		case 'edit': doEditGroup('edit');break;
		case 'search':doHosDictGroupSearch();break;
		case 'del':doDelGroup('del');break;
	}
}
//初始化按钮Form
function doOnButtFormInit(){
	if (typeof (buttForm) == 'object') {
		buttForm.attachEvent("onButtonClick",function(name,command) {
			switch (command) {
			case 'add':doEdit('add');break;
			case 'edit':doEdit('edit');break;
			case 'refresh':doRefresh();break;
			}
		});
	}
}
function initHosDictGrid() {
	hosDictGrid = layoutContainer.grid[1];
	dmjplugs.grid.createGrid({
		  sm:'ch',
		  skin:'dhx_skyblue',
		  srcc:true,
		  validate : true,
		  columns:[ {header:'id',id:'id',width:10,hidden:true},
			       	{header:'字典名称',id:'group_name',width:120},
			    	{header:'字典编码',id:'group_code',width:80,hidden:true},
			    	{header:'枚举名称',id:'dict_name',width:'*'},
			    	{header:'枚举编码',id:'dict_code',width:150},
			    	{header:'扩展数据项',id:'ext_value',width:100,hidden:true},
			    	{header:'数据创建时间',id:'gmt_create',width:120,hidden:true},
			    	{header:'数据修改时间',id:'gmt_modify',width:120,hidden:true},
			 		 {header:'状态',id:'status',width:100,type:'combo',hidden:true},
			    	{header:'推荐排序',id:'sort_num',width:90},
			    	{header:'操作人员',id:'operator',width:'*',hidden:true},
			        {header:'备注',id:'remark',width:120}
                 ]
	},hosDictGrid);
	hosDictGrid.setTotal(0);
	hosDictGrid.getColumnCombo(hosDictGrid.getColIndexById('status')).addOption(statusComboData);
	hosDictGrid.enableEditEvents(false,false,false);
	hosDictGrid.setColumnHidden(0,true);
	hosDictGrid.attachEvent("loadPagingData", function(first, limit){
		loadHosDictData(first, limit);
	});
	hosDictGrid.attachEvent("onRowDblClicked", function(){
		doEdit('edit');
	});
}
function initHosDictGroupGrid() {
	hosDictGroupGrid = layoutContainer.grid[0];
	dmjplugs.grid.createGrid({
		  sm:'ch',
		  skin:'dhx_skyblue',
		  srcc:true,
		  validate : true,
		columns:[
			{header:'id',id:'id',width:10,hidden:true},
			{header:'group_code',id:'group_code',width:10,hidden:true},
			{header:'字典名称',id:'group_name',width:'*'},
			{header:'备注',id:'remark',width:120}
		]
	},hosDictGroupGrid);
	hosDictGroupGrid.setTotal(0);
	hosDictGroupGrid.enableEditEvents(false,false,false);
	hosDictGroupGrid.setColumnHidden(0,true);
	//hosDictGroupGrid.getColumnCombo(hosDictGroupGrid.getColIndexById('level')).addOption(natures);
	hosDictGroupGrid.attachEvent("onRowSelect",doOnRowSelected);
	hosDictGroupGrid.attachEvent("onRowDblClicked",function () {
		doEditGroup('edit');
	});
}

function loadHosDictData(first,limit) {
	if (!limit) {
		first = 0;
		limit = hosDictGrid.getPageRowLimit();
		hosDictGrid.clearAll();
		hosDictGrid.setTotal(0);
	}
	/*if(!s_groupCode){
		$func.alert("请先选择", "red");
		return;
	}*/
	var searchType=1;
	var searchKey=hosDictToolbar.getValue("hosDictSearchKey");
	if(searchKey=='输入枚举名称') searchKey='';
	layoutContainer.layout.progressOn("加载枚举数据中...");
	var postData="pageNo="+parseInt(first/limit+1)+"&pageSize="+limit+"&pageCount="+hosDictGrid.getPageTotal()+"&groupCode="+s_groupCode;
	if(searchType==1&&searchKey&&searchKey!="") postData+="&dictName="+$.trim(searchKey);
	$.ajax({
        url: basePath+'dict/findSysDictGrid',
        type: 'post',
        dataType: 'json',
        data:encodeURI(postData),
        success: function (data) {
            if(data&&data.rowCount>0){
            	hosDictGrid.parse(data.gridr, "json");
            	hosDictGrid.setTotal(data.rowCount);
            	hosDictGrid.uncheckAll();
            }
            layoutContainer.layout.progressOff();
        },
		error:function (XMLHttpRequest, textStatus, statustText) {
 			layoutContainer.layout.progressOff();
		}
    });
}

//加载信息数据
function doHosDictSearch(first,limit){
	if(!s_groupCode){
		$func.alert("请先选择一行左侧字典再操作", "red");
		return;
	}
	var searchType=1;
	var searchKey=hosDictToolbar.getValue("hosDictSearchKey");
	/*if(!searchKey||searchKey==0){
		$func.alert("请先填写", "red");
		return;
	}*/
	if(searchKey=='输入枚举名称') searchKey='';
	if (!limit) {
		hosDictGrid.setTotal(0);
		hosDictGrid.clearAll();
		first = 0;
		limit = hosDictGrid.getPageRowLimit();
	}
	var postData="pageNo=1&pageSize="+limit+"&pageCount="+hosDictGrid.getPageTotal();
	if(searchType==1&&searchKey&&searchKey!="") postData+="&dictName="+$.trim(searchKey);
	if(s_groupCode&&s_groupCode!="") postData+="&groupCode="+s_groupCode;

 	$.ajax({
        url: basePath+'dict/findSysDictGrid',
        type: 'post',
        dataType: 'json',
        data:encodeURI(postData),
        success: function (data) {
            if(data&&data.rowCount>0){
            	hosDictGrid.parse(data.gridr, "json");
            	hosDictGrid.setTotal(data.rowCount);
				hosDictGrid.uncheckAll();
            }
        }
    });
}
function doHosDictGroupSearch(vContent){ //加载信息数据 ,先索引后数据库
	hosDictToolbar.setValue("hosDictSearchKey", "输入枚举名称");
	var searchType=1; //search_Form.getItemValue("docSearchType") ;
	var searchKey=hosDictGroupToolbar.getValue("hosDictGroupContent"); //search_Form.getItemValue("hosDictSearchKey") ;
	if(vContent) searchKey=vContent;
	if(searchKey && searchKey=='输入字典名称') searchKey='';
	hosDictGroupGrid.setTotal(0);
	hosDictGroupGrid.clearAll();
	var postData="dictName="+$.trim(searchKey);
 	$.ajax({
        url: basePath+'dict/findAllSysDictGroupGrid',
        type: 'post',
        dataType: 'json',
        data:encodeURI(postData),
		success: function(data, textStatus, jqXHR) {
			if(!data) {
 				return false;
 			}
			hosDictGroupGrid.setTotal(data.rowCount);
			hosDictGroupGrid.parse(data.gridr, "json");
			hosDictGroupGrid.uncheckAll();
        },
		error:function (XMLHttpRequest, textStatus, statustText) {
			$func.alert("获取字典分组列表失败" , "red");
		}
    });


}
function doEdit(type){
	var level=1;
	/*if(!s_groupCode){
		$func.alert("请先选择", "red");
		return;
	}*/
	if(type!='add'&&type!='edit')
		return;
	var docs = getCheckedRowsByGrid(hosDictGrid, hosDictGrid.getColIndexById('select'));
	if (type=='edit'&&(docs == null||docs.length > 1)) {
		$func.alert("请选择一行枚举再编辑", "red");
		return;
	}
	var group = getCheckedRowsByGrid(hosDictGroupGrid, hosDictGroupGrid.getColIndexById('select'));
	if (type=='add'&&group != null&&group.length == 1) {
		oneHosDictGroupInfo = group[0];
	} else {
		oneHosDictGroupInfo = null;
	}
	if(type=='add'&&(group == null || group.length != 1)){
		$func.alert("请选择一行左侧字典再新增", "red");
		return;
	}
	if(type=='edit'){
		oneHosDictInfo = docs[0];
		checkParam(docs[0].id);
	} else {
		rondomNum = getRandomNum();
		checkParam(rondomNum);
	}
	if(!dhxWins)dhxWins=new dhtmlXWindows();
	dhxWins.setImagePath(basePath + "public/js/dhtmlx/dhtmlxWindows/codebase/imgs/");
	editHosDictWin = dhxWins.createWindow("editHosDictWin", 2, 2, 300, 360);
	editHosDictWin.center();
	editHosDictWin.setModal(true);
	editHosDictWin.bringToTop();
	editHosDictWin.setText("<span style=\"font-size:14px;\">"+(type=="add"?"新增枚举":"编辑枚举")+"</span>");
	editHosDictWin.denyResize();
	editHosDictWin.button("minmax1").hide();
	editHosDictWin.button("park").hide();
	editHosDictWin.attachURL(basePath+"dict/editPage?type="+type+"&level="+level);
}

function doEditGroup(type){
	if(type!='add'&&type!='edit')
		return;
	var docs = getCheckedRowsByGrid(hosDictGroupGrid, hosDictGroupGrid.getColIndexById('select'));
	if (type=='edit'&&(docs == null||docs.length > 1)) {
		$func.alert("请选择一行再编辑", "red");
		return;
	}
	if(type=='edit'){
		oneHosDictGroupInfo = docs[0];
		checkParam(docs[0].id);
	} else {
		rondomNum = getRandomNum();
		checkParam(rondomNum);
	}
	if(!dhxWins)dhxWins=new dhtmlXWindows();
	dhxWins.setImagePath(basePath + "public/js/dhtmlx/dhtmlxWindows/codebase/imgs/");
	editHosDictGroupWin = dhxWins.createWindow("editHosDictGroupWin", 2, 2, 300, 250);
	editHosDictGroupWin.center();
	editHosDictGroupWin.setModal(true);
	editHosDictGroupWin.bringToTop();
	editHosDictGroupWin.setText("<span style=\"font-size:14px;\">"+(type=="add"?"新增字典":"编辑字典")+"</span>");
	editHosDictGroupWin.denyResize();
	editHosDictGroupWin.button("minmax1").hide();
	editHosDictGroupWin.button("park").hide();
	editHosDictGroupWin.attachURL(basePath+"dict/editGroupPage?type="+type);
}

//选中一行
function doOnRowSelected(rowID, celInd) {
	hosDictToolbar.setValue("hosDictSearchKey", "输入枚举名称");
	hosDictGrid.clearAll();
	hosDictGrid.setTotal(0);
	hosDictGroupGrid.cells(rowID, hosDictGroupGrid.getColIndexById('select')).setValue(1);
	s_groupCode=hosDictGroupGrid.cells(rowID, hosDictGroupGrid.getColIndexById('group_code')).getValue();
	if(!s_groupCode||s_groupCode.length==0)
		return false;
	loadHosDictData();
}
function removeHTMLTag(str) {
	if(!str) return '';
    str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
    str = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
    //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    str=str.replace(/&nbsp;/ig,'');//去掉&nbsp;
    return str;
}
//刷新操作
function doRefresh(){
	/*hosDictGrid.clearAll();
	hosDictGrid.setTotal(0);
 	loadHosDictData();*/
	hosDictGroupGrid.clearAll();
	hosDictGroupGrid.setTotal(0);
	doHosDictGroupSearch();
	if(s_groupCode){
		hosDictGrid.clearAll();
		hosDictGrid.setTotal(0);
		loadHosDictData();
	}
}

function doRefreshDict(){
	/*hosDictGrid.clearAll();
	 hosDictGrid.setTotal(0);
	 loadHosDictData();*/
	//字电内容编辑不重新刷新字典分组
	// hosDictGroupGrid.clearAll();
	// hosDictGroupGrid.setTotal(0);
	// doHosDictGroupSearch();
	if(s_groupCode){
		hosDictGrid.clearAll();
		hosDictGrid.setTotal(0);
		loadHosDictData();
	}
}

function doReset(){
  	search_Form.getCombo('subject').setComboValue('');
	search_Form.setFormData({
		searchDocKey:'',
 	});
}

function doDelGroup(type){
	//校验
	if(type!='del') return;
	//先选择
	var dicts = getCheckedRowsByGrid(hosDictGroupGrid, hosDictGroupGrid.getColIndexById('select'));
	if (type=='del'&&(dicts == null||dicts.length > 1) ) {
		$func.alert("请选择一个字典分组再操作", "red");
		return;
	}
	checkParam(dicts[0].id);
	var confirmArr = "是否删除字典【"+dicts[0].group_name+"】？ <br><font color='#ff66;'>该操作会变更字典数据！</font>";
	$func.confirm({
		content : confirmArr,
		ok : function() {
			var json = {'id':dicts[0].id};
			$.ajax({
				url: basePath+'dict/delSysDict',
				type: 'post',
				dataType: 'json',
				contentType:"application/json",
				data:JSON.stringify(json),
				success: function (back) {
					if(!back||!back.result){
						$func.alert(back.message?back.message:"删除失败", "red");
						return;
					}
					$func.alert("删除成功！", "green");
					// doRefresh();

					hosDictGroupGrid.clearAll();
					hosDictGroupGrid.setTotal(0);
					doHosDictGroupSearch();

					//清空右侧枚举grid
					hosDictGrid.clearAll();
					hosDictGrid.setTotal(0);
				}
			});
		}
	});
}

function doDel(type){
	//校验
	if(type!='del') return;
	//先选择
	var dicts = getCheckedRowsByGrid(hosDictGrid, hosDictGrid.getColIndexById('select'));
	if (type=='del'&&(dicts == null||dicts.length > 1) ) {
		$func.alert("请选择一行枚举再操作", "red");
		return;
	}
	checkParam(dicts[0].id);
	var confirmArr = "是否删除枚举【"+dicts[0].dict_name+"】？ <br><font color='#ff66;'>该操作会变更字典枚举数据！</font>";
	$func.confirm({
		content : confirmArr,
		ok : function() {
			var json = {'id':dicts[0].id};
			$.ajax({
				url: basePath+'dict/delSysDict',
				type: 'post',
				dataType: 'json',
				contentType:"application/json",
				data:JSON.stringify(json),
				success: function (back) {
					if(!back||!back.result){
						$func.alert(back.message?back.message:"删除失败", "red");
						return;
					}
					$func.alert("删除成功！", "green");
					doRefreshDict();
				}
			});
		}
	});
}
